package cn.cnf.service.impl;

import cn.cnf.common.enums.MoneyRecordType;
import cn.cnf.common.enums.WorkType;
import cn.cnf.common.exception.CustomException;
import cn.cnf.common.utils.BigDecimalUtil;
import cn.cnf.entity.MoneyRecord;
import cn.cnf.entity.User;
import cn.cnf.mapper.MoneyRecordMapper;
import cn.cnf.service.ComicService;
import cn.cnf.service.MoneyRecordService;
import cn.cnf.service.NovelService;
import cn.cnf.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 服务接口实现
 *
 * @author ZhuMeiYi
 * @since 2021-01-10 23:11:44
 * @description 
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Service
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public class MoneyRecordServiceImpl extends ServiceImpl<MoneyRecordMapper, MoneyRecord> implements MoneyRecordService {

    private final MoneyRecordMapper moneyRecordMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private ComicService comicService;
    @Autowired
    private NovelService novelService;


    @Override
    public boolean addRecord(String fromId, String fromName, String toId, String toName, BigDecimal num, MoneyRecordType type) {
        // 录入记录
        MoneyRecord moneyRecord = new MoneyRecord();
        moneyRecord.setFromId(fromId);
        moneyRecord.setFromName(fromName);
        moneyRecord.setToId(toId);
        moneyRecord.setToName(toName);
        moneyRecord.setNum(num);
        moneyRecord.setType(type.getValue());
        int insert = moneyRecordMapper.insert(moneyRecord);
        return insert == 1;
    }

    @Override
    public IPage<MoneyRecord> getRecord(Integer current, Integer pageSize,String fromName,String toName,MoneyRecordType type,String time) {
//        LambdaQueryWrapper<MoneyRecord> wrapper = new LambdaQueryWrapper<MoneyRecord>()
//                .eq(fromName!=null,MoneyRecord::getFromName, fromName)
//                .eq(toName!=null,MoneyRecord::getToName, toName);
//        if (type!=null){
//            wrapper.eq(MoneyRecord::getType,type.getValue());
//        }
        // 分页
        Page<MoneyRecord> page = new Page<>(current, pageSize);

        return moneyRecordMapper.getRecord(page,time,fromName,toName,type.getValue());
//        return moneyRecordMapper.selectPage(page, wrapper);
    }

    @Override
    public String rewardsWork(String username, String workId, WorkType type, BigDecimal money) {
        // 来源
        User fromUser = userService.findUserByUsername(username);
        String authorId ="";
        // 如果是漫画
        if (type==WorkType.COMIC){
            // 作者
            authorId = comicService.getById(workId).getAuthorId();
            comicService.adjustComicMoneyById(workId, money);
        }else if (type == WorkType.NOVEL){
            // 作者
            authorId = novelService.getById(workId).getAuthorId();
            novelService.adjustNovelMoneyById(workId,money);
        }else {
            throw new CustomException("未知的作品类型");
        }
        // 执行转账
        transferMoney(fromUser.getId(),authorId,money);
        return workId;
    }

    @Override
    public BigDecimal adjustUserMoney(String useKey, BigDecimal num, boolean idOrName) {
        User user;
        if (idOrName) {
            user = userService.getById(useKey);
        } else {
            user = userService.findUserByUsername(useKey);
        }
        // 计算余额
        BigDecimal result = BigDecimalUtil.safeAdd(user.getMoney(), num);
        if (BigDecimalUtil.greaterThan(result, BigDecimal.ZERO)) {
            // 如果余额大于0 则
            // 添加调整记录
            addRecord(user.getId(), user.getUsername()
                    , null, null, num
                    , BigDecimalUtil.greaterThan(num, BigDecimal.ZERO) ? MoneyRecordType.CHONGZHI : MoneyRecordType.TIXIAN);

        } else if (BigDecimalUtil.lessThan(result, BigDecimal.ZERO)) {
            // 如果余额小于0 则
            throw new CustomException("余额不足");
        }
        user.setMoney(result);
        userService.updateById(user);
        return user.getMoney();
    }

    @Override
    public boolean transferMoney(String fromId, String toId, BigDecimal num) {
        // 判断是否超额
        User from = userService.getById(fromId);
        BigDecimal fromResult = BigDecimalUtil.safeSubtract(from.getMoney(), num);
        if (BigDecimalUtil.lessThan(fromResult, BigDecimal.ZERO)) {
            throw new CustomException("余额不足");
        }
        // 来源减钱
        from.setMoney(fromResult);
        userService.updateById(from);
        // 去向加钱
        User to = userService.getById(toId);
        to.setMoney(BigDecimalUtil.safeAdd(to.getMoney(), num));
        // 保存
        userService.updateById(to);
        // 录入转账记录
        addRecord(fromId, from.getUsername(), toId, to.getUsername(), num, MoneyRecordType.ZHUANZHANG);

        return true;
    }
}